package com.java1412.web.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.java1412.common.utils.ConstantUtil;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Map;

/**
 * jwt的工具类
 *
 * @author java1412
 * @since 2025-05-20 14:14
 */
@Component
public class JWTUtil {

    // 密钥
    private final static String TOKEN = "token!Q2W#E$RW";

    /**
     * 获取令牌
     *
     * @param map 传进去负载
     * @return
     */
    public String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, ConstantUtil.JWT_TIME_OUT);
        builder.withExpiresAt(calendar.getTime());
        return builder.sign(Algorithm.HMAC256(TOKEN)).toString();
    }

    /**
     * 验证token
     *
     * @param token
     * @return
     */
    public DecodedJWT verify(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(TOKEN)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT;
    }

    /**
     * 获取token中payload
     *
     * @param token
     * @return
     */
    public static DecodedJWT getToken(String token) {
        return JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }
}
